package kjj.android.ch9.app;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.WriteAbortedException;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidDataActivity extends Activity {
	private EditText etMsg;
	private Button btnSend;
	private static final String temp_MSG = "temp_sms";
	private static final String FILE_NAME = "kjjfile.txt";

	private Button btnWf;
	private Button btnRf;
	private EditText textWf;
	private TextView tvRf;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		btnSend = (Button) findViewById(R.id.buttonSendMsg);
		etMsg = (EditText) findViewById(R.id.editTextMsg);

		//obtain sharedpreference interface
		SharedPreferences preferences = 
			getSharedPreferences(temp_MSG, MODE_WORLD_READABLE);
		String contentString = preferences.getString("sms_content", "");
		etMsg.setText(contentString);
		
		btnRf = (Button)findViewById(R.id.buttonRf);
		btnWf = (Button)findViewById(R.id.buttonWf);
		textWf = (EditText)findViewById(R.id.editTextWf);
		tvRf	 = (TextView)findViewById(R.id.textViewRead);
		
		btnWf.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				write(textWf.getText().toString());
			}
		});
		btnRf.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tvRf.setText(read());
			}
		});
	}
	
	private String read(){
		try {
			FileInputStream fis = openFileInput(FILE_NAME);
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			return new String(buffer);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	
	private void write(String text){
		try {
			FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
			fos.write(text.getBytes());
			fos.close(); //flush on purpose.
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		//save temporal message
		SharedPreferences.Editor prefEditor = 
			getSharedPreferences(temp_MSG, MODE_WORLD_WRITEABLE)
			.edit();

		prefEditor.putString("sms_content", etMsg.getText().toString());
		prefEditor.commit(); //save to file on the permenant storage
	}
}